from base.request_new import RequestNew
from business.tour.template.api_template import *
from bson import json_util
from business.tour.extract_resource import dispatcher
from business.tour.template.category_config import tour_category_cfg
from business.tour.template.property_config import tour_property_cfg
from business.tour.template.studycenter_config import tour_studycenter_cfg
from base.logcontrol import logger
from business.ssologin.login import user_login
from business.tour.template.tourAssignment_config import tour_assignment_cfg


class Checker:

    def __init__(self):
        cookies = user_login()
        self.rt = RequestNew(cookie=cookies)

        # 收集未处理的资源，暂未使用
        self.warnings = list()

    def api_exec(self, template_name):
        """
        获取趣游学配置资源
        :return: 字典
        """
        _vars = {}
        for req in template_name:
            try:
                req_data_keys = req["data"].keys()
            except AttributeError:
                req_data_keys = {}
            same = _vars.keys() & req_data_keys
            if same:
                for key in same:
                    req["data"].update({key: _vars[key]})
            res, get_vars = self.rt.request_auto(**req)
            _vars.update(get_vars)
        return _vars

    def get_category(self, template):
        """
        提取接口返回的资源列表
        :param template: 接口配置见api_template.py
        :return:
        """
        try:
            resource = self.api_exec(template)
        except Exception as ce:
            msg = f"获取获取趣游学资源时异常：{ce}"
            logger.error(f"\n\t{msg}\n")
            raise RuntimeError(msg)

        resources = {}
        try:
            for name, conf_id in resource.items():
                if not conf_id:
                    logger.warning(f"\n\t{name}没有取到id，请检查api_template配置\n")
                    continue
                r, contents = self.rt.request_auto(**conf_data(digest_id=conf_id))
                content_list = contents["contentList"]
                if content_list:
                    resources.update({name: content_list})
                else:
                    logger.warning(f"\n\t获取{name}时，返回了空\n")
            return resources
        except Exception as e:
            msg = f"解析CONF_DATA异常：{e}"
            logger.error(f"\n\t{msg}\n")
            raise RuntimeError(msg)

    #  微信机器人报警
    def send_msg(self, content, rob_key):
        wx_url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={rob_key}"
        """艾特全部，并发送指定信息"""
        person = ["@all"]
        req = {
            "url": wx_url,
            "data": {
                "msgtype": "text",
                "text": {"content": content, "mentioned_list": person}
            },
            "method": "POST",
            "content_type": "JSON",
            "ignore": True
        }
        r, _ = self.rt.request_auto(**req)
        logger.debug(f"企微发送结果：{r}")
        return r

    def get_resources(self, tour_api_template, tour_cfg):
        # 按接口模板获取数据
        try:
            resources = self.get_category(tour_api_template)
        except Exception as e:
            logger.error(f"\n\tget_resources：获取{tour_api_template}接口数据异常：{e}\n")
            raise RuntimeError()

        # 读取提取元素模板
        cfg_list = tour_cfg(resources)

        # 批量提取元素
        category_resources = {}
        try:
            for cfg in cfg_list:
                r = dispatcher(**cfg)
                category_resources.update(r)
                logger.info(f"\n\t{cfg['key']}提取结果：{r}\n")
                resources.pop(cfg["key"])
        except Exception as e:
            logger.error(f"\n\t提取分组{tour_api_template}资源异常：{e}\n")
            raise RuntimeError()
        if resources:
            not_exec_resource = list(resources.keys())
            self.warnings.extend(not_exec_resource)
            logger.warning(f"\n\t{not_exec_resource}未处理，请添加模板\n")
        return category_resources

    @classmethod
    def compare(cls, category_group_resources, tour_static):
        """
        :param category_group_resources: 资源dict
        :param tour_static: 比较对象set
        :return:
        """
        compare_result = list()
        for key in category_group_resources:
            temp = {}
            diff = category_group_resources[key].difference(tour_static)
            if diff:
                temp.update({
                    "config_key": key,
                    "check_result": "未通过",
                    "diff": diff
                })
            else:
                temp.update({
                    "config_key": key,
                    "check_result": "通过"
                })
            logger.info(f"\n\t{key}的检查结果:{temp}\n")
            compare_result.append(temp)
        return compare_result

    def checker(self):
        ret = list()
        # 获取category分组资源

        # 道具包id

        # 道具id

        # 非道具资源汇总
        

        # 获取property分组资源
       
        # 道具id&道具图片资源汇总
        
        # 道具包id&包中道具id汇总
       

        # 道具图片资源
      
        # 获取学习中心分组资源
       
        # 道具包id
       

        # 获取趣游学任务分组资源
       
        # 道具包
       
        # 比较非道具图片资源
       

        # 比较道具类
        # 1、道具id
 

        # 2、道具图片
 

        # 3、道具包
  

        return ret

    def do_check(self):
        r = self.checker()
        res = json_util.dumps({"资源检查": r}, indent=1, ensure_ascii=False)
        logger.info(f"\n\t本次检查结果：{res}\n")
        # self.send_msg(content=res, rob_key="")
        return res
